package org.eclipseuseradmin.ui.model;

import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipseuseradmin.internal.ui.wizards.WizardsMessages;
import org.eclipseuseradmin.ui.IRoleElement;
import org.osgi.service.useradmin.UserAdmin;

public class RoleElementModel {

	private UserAdmin userAdmin;

	protected IRoleElement roleElement;

	protected String name;

	protected IValidator nameValidator;

	public RoleElementModel(UserAdmin userAdmin) {
		this.userAdmin = userAdmin;
	}

	public RoleElementModel(UserAdmin userAdmin, IRoleElement roleElement) {
		this(userAdmin);
		this.roleElement = roleElement;
	}

	public void save() {

	}

	public IRoleElement create() {
		return null;
	}

	public boolean exists(String name) {

		return userAdmin.getRole(name) != null;
	}

	public String getName() {

		if (name != null) {
			return name;
		}
		if (roleElement != null) {
			return roleElement.getName();
		}
		return null;
	}

	public void setName(String name) {
		this.name = name;
	}

	public IValidator getNameValidator() {

		if (nameValidator == null) {
			nameValidator = new IValidator() {
				public IStatus validate(Object value) {
					if (((String) value).length() == 0) {
						return ValidationStatus
								.error(WizardsMessages.get().NewRoleElementWizardPage_error_name_empty);
					}
					if (exists(((String) value))) {
						return ValidationStatus
								.error(WizardsMessages.get().NewRoleElementWizardPage_error_name_exists);
					}
					return ValidationStatus.OK_STATUS;
				}
			};
		}
		return nameValidator;
	}

	protected UserAdmin getUserAdmin() {
		return userAdmin;
	}
}
